<template>
    <cardComponent class="ConsumeInstallment" v-loading="isLoading" pageTitle="消费分期申请">
        <template slot="cardBody">
            <el-form ref="dailyFormRef" :model="dailyForm" label-width="120px" size="small">
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="账户类别:" class="text_fl">
                            <el-select
                                v-model="searchForm.accttype"
                                placeholder="请选择账户类别"
                                disabled
                                @change="changeCardList"
                            >
                                <el-option
                                    v-for="item in AccountionTYPE_INFO"
                                    :label="item.label"
                                    :value="item.code"
                                    :key="item.label"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="卡号:" class="text_fl">
                            <el-select v-model="searchForm.cardno" placeholder="请选择卡号" disabled>
                                <el-option
                                    v-for="item in cardList"
                                    :label="item.CARDNBR"
                                    :value="item.CARDNBR"
                                    :key="item.CARDNBR"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="分期计划编号:">
                            <el-select
                                placeholder="请选择信用计划编号"
                                @change="getCREDNOValue"
                                v-model="dailyForm.CREDNO"
                                clearable
                            >
                                <el-option
                                    v-for="(item, index) in CREDNOLIST"
                                    :key="index"
                                    :label="item.code + ' -- ' + item.label"
                                    :value="item.code"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :span="3">
                        &nbsp;&nbsp;
                        <el-button type="primary" size="small" @click="searchData">查 询</el-button>
                    </el-col>-->
                </el-row>
                <!-- <el-form-item size="large" label-width="0">
                    <el-button type="primary" size="small" @click="searchData">查 询</el-button>
                    <el-button type="primary" size="small"  plain @click="unBillChecked">未出账单查询</el-button>
                    <el-button type="primary"  size="small" plain @click="onMptransQuery">分期付款交易明细查询</el-button> 
                </el-form-item>-->
            </el-form>
            <div v-if="showTrial">
                <el-table
                    :data="trailTable"
                    border
                    stripe
                    class="heard-bg business_table"
                    @selection-change="multipleChange"
                >
                    <el-table-column type="selection" width="70"></el-table-column>

                    <el-table-column label="交易日" show-overflow-tooltip width="180">
                        <template slot-scope="scope">
                            <span>{{ scope.row.PURTIME | getFormatDate(scope.row.VALDATE) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="记账日">
                        <template slot-scope="scope">
                            <span>{{scope.row.PURDATE | formatDate}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="交易金额">
                        <template slot-scope="scope">
                            <span
                                v-if="scope.row.AMTFLAG !== '+'"
                            >{{scope.row.AMTFLAG}}{{scope.row.AMOUNT.toFixed(2)}}</span>
                            <span v-else>{{scope.row.AMOUNT.toFixed(2)}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="TRANTYPE" label="交易类型"></el-table-column>
                    <el-table-column label="卡号末四位">
                        <template slot-scope="scope">
                            <span>{{scope.row.CARDEND | formatCardend}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="DESLINE1" label="交易描述"></el-table-column>
                    <el-table-column label="消费分期标志">
                        <template slot-scope="scope">
                            <span>{{scope.row.MPFLAG === 1 ? '已申请' : '无'}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="NBRMTHS" label="消费分期期数"></el-table-column>
                </el-table>

                <el-divider content-position="center">费用试算</el-divider>
                <el-form label-width="120px" size="small">
                    <el-row>
                        <el-col :span="10">
                            <el-form-item label="总金额:" class="text_fl">
                                <span class="el-form-item-span">{{totalAmount}}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="10">
                            <el-form-item label="选择分期期数:" class="text_fl">
                                <el-select
                                    placeholder="请选择转分期期数"
                                    clearable
                                    filterable
                                    value-key="MPMONTH"
                                    v-model="dailyForm.NBRMTHS"
                                    @change="handleGetComputeMP"
                                >
                                    <el-option
                                        v-for="item in MPMONTH_Option"
                                        :key="item.MPMONTH"
                                        :label="item.label"
                                        :value="item"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="20" :offset="1">
                            <div class="text_center">
                                <el-form-item label="费用试算表:" label-position="left">
                                    <template>
                                        <el-table
                                            :data="Trial_table"
                                            border
                                            stripe
                                            style="width:100%"
                                            class="el-table heard-bg"
                                        >
                                            <el-table-column label="总还款额" prop="totalRepayment"></el-table-column>
                                            <el-table-column label="总手续费" prop="totalHandling"></el-table-column>
                                            <el-table-column label="每月本金" prop="monthsPrincipal"></el-table-column>
                                            <el-table-column
                                                v-if="this.MPMONTH_Option_one.PMmethod==='1'"
                                                label="每月手续费"
                                                prop="monthlyService"
                                            ></el-table-column>

                                            <el-table-column
                                                v-if="this.MPMONTH_Option_one.PMmethod==='1'"
                                                label="每月还款额"
                                                prop="monthlyPayment"
                                            ></el-table-column>
                                            <el-table-column
                                                v-if="this.MPMONTH_Option_one.PMmethod==='0'"
                                                label="首期还款额"
                                                prop="fstPayment"
                                            ></el-table-column>
                                        </el-table>
                                    </template>
                                </el-form-item>
                            </div>
                        </el-col>
                    </el-row>
                </el-form>
                <!-- 话术 -->
                <div class="hstable_wrap" v-if="speechList.length!=0">
                    <el-table
                        :data="speechList"
                        border
                        stripe
                        header-row-class-name="headerRow"
                        ref="showListTable"
                        class="heard-bg business_table hstable"
                        @selection-change="handleSelectionChange"
                    >
                        <el-table-column type="selection" label=" " min-width="55"></el-table-column>
                        <el-table-column label="业务话术">
                            <template slot-scope="scope">{{scope.row.content}}</template>
                        </el-table-column>
                    </el-table>
                </div>
                <!-- 办理结果页面 -->
                <div v-show="step3Page" style="margin:5px 90px 5px 175px;">
                    <el-table
                        :data="resultList"
                        style="width: 93%"
                        border
                        class="table_head heard-bg setbottomborder"
                        :stripe="true"
                    >
                        <el-table-column label="申请结果">
                            <el-table-column label="金额" min-width="30">
                                <template slot-scope="scope">{{ scope.row.amount }}</template>
                            </el-table-column>
                            <el-table-column label="期数" min-width="30">
                                <template slot-scope="scope">{{ scope.row.months }}</template>
                            </el-table-column>
                            <el-table-column label="手续费分摊方式" min-width="50">
                                <template slot-scope="scope">{{ scope.row.pmMethod }}</template>
                            </el-table-column>
                            <el-table-column label="办理结果" min-width="80">
                                <template slot-scope="scope">{{ scope.row.handleResult }}</template>
                            </el-table-column>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="footer">
                    <el-button type="primary" size="small" @click="handleClicksuInfo">多期数试算结果</el-button>
                    <el-button type="primary" size="small" @click="handleApplication">申 请</el-button>
                    <el-button
                        type="primary"
                        size="small"
                        @click="applicationRecords"
                        v-show="step3Page"
                    >分期付款申请记录</el-button>
                </div>
                <el-dialog
                    v-drag
                    :visible.sync="DialogVisible"
                    width="1200px"
                    :append-to-body="true"
                    top="20vh"
                    :close-on-click-modal="false"
                    center
                >
                    <trialbalance :TrialDataList="TrialDataList"></trialbalance>
                    <span slot="footer" class="dialog-footer">
                        <!-- <el-button size="small" @click="DialogVisible = false">取 消</el-button> -->
                        <el-button type="primary" size="small" @click="DialogVisible = false">关 闭</el-button>
                    </span>
                </el-dialog>
                <el-dialog
                    title="多期数试算结果"
                    v-drag
                    :visible.sync="DialogVisible1"
                    width="1200px"
                    :append-to-body="true"
                    top="20vh"
                    :close-on-click-modal="false"
                    center
                >
                    <trialbalance1 :TrialDataList="TrialDataList"></trialbalance1>
                    <span slot="footer" class="dialog-footer">
                        <!-- <el-button size="small" @click="DialogVisible = false">取 消</el-button> -->
                        <el-button type="primary" size="small" @click="DialogVisible1 = false">关 闭</el-button>
                    </span>
                </el-dialog>
            </div>
            <!-- 二次确认办理弹窗 -->
            <el-dialog
                v-drag
                title="消费分期申请确认"
                :visible.sync="secConfirmDialogVisible"
                width="500px"
                :append-to-body="true"
                top="30vh"
                :close-on-click-modal="false"
                center
            >
                <p>
                    办理笔数：
                    <span>{{this.secondConfirm.handleNum}}</span>
                </p>
                <p>
                    总金额:
                    <span>{{this.secondConfirm.totalAmount}}</span>
                </p>
                <p>
                    期数:
                    <span>{{this.secondConfirm.months}}</span>
                </p>
                <p>
                    手续费分摊方式:
                    <span>{{this.secondConfirm.pmMethod}}</span>
                </p>
                <p style="text-align:center;padding-left:0px;">
                    <span style="color:#3a8ee6; ">您确认要申请吗？</span>
                </p>
                <span slot="footer" class="dialog-footer">
                    <el-button
                        size="small"
                        icon="el-icon-circle-close"
                        @click="secConfirmDialogVisible = false"
                    >取 消</el-button>
                    <el-button
                        type="primary"
                        size="small"
                        @click="secConfirmYes"
                        icon="el-icon-circle-check"
                    >确定</el-button>
                </span>
            </el-dialog>

            <!-- 申请成功窗口 -->
            <ConfirmWindow
                v-if="showsuccess"
                @isShow="close"
                :dataList="statementsuccess"
                :title="'消费分期申请成功！'"
            />
        </template>
    </cardComponent>
</template>

<script>
import { mapState } from 'vuex';
import moment from 'moment';
import { getInstalmentList, getAccountTypeName, getDictSelectList, getBusinessMenuId } from '@/utils/Common';
import cardComponent from '@/components/cardComponent/cardComponent.vue';
import ConfirmWindow from '@/components/ConfirmWindow/ConfirmWindow.vue';
import { isEmptyObject, setNumber, ChangePage } from '@/utils/Object';
import { get_4xxx, get_3xxx } from '@/apis/getAPIClass';
import Trialbalance from '@/components/TrialBalance/Trialbalance';
import Trialbalance1 from '@/components/TrialBalance/Trialbalance1';

export default {
    name: 'ConsumeInstallment',
    components: {
        cardComponent,
        ConfirmWindow,
        Trialbalance,
        Trialbalance1,
    },
    data() {
        return {
            dailyForm: {
                CATEGORY: '', // 3076
                CUSTRNAME: '', // 3076
                CARDNO: '', // 卡号
                CREDNO: '', // 信用计划编号
                MPAMT: '', // 分期金额
                NBRMTHS: '', // 分期期数
            },

            showsuccess: false,
            statementsuccess: [],
            CREDNOLIST: [], // 信用计划编号 下拉选择列表
            trailTable: [],
            showTrial: false,
            isLoading: false,
            pagingDataList: [], // 翻页上送字段列表
            currentPageIndex: 0, // 当前页下一页’  按钮的显示控制阀
            nextButtonFlag: true, // 下翻页按钮 显示控制阀
            isChecked: {},
            setMonthRate: [],
            tryData: [
                {
                    OUTFLAG: '3', //存期数
                    CORPUS: 0,
                    REMONTHFEE: 0,
                    ALLMONTHSFEE: 0,
                    ALLCOUNTFEE: 0,
                    MPIRR: 0,
                    TRYDATA1: 0,
                    TRYDATA2: 0,
                    TRYDATA3: 0,
                    TRYDATA4: 0,
                },
            ],
            currentRow: null,
            PURDATE: '',
            VALDATE: '',
            PURTIME: '',
            TRANNO: '',
            searchForm: { // 账户类型、卡号双选字段
                accttype: '',
                cardno: '',
            },
            cardList: [],
            MPMONTH_list: [],//分期期数列表
            MPMONTH_Option: [],//分期期数下拉
            MPMONTH_Option_one: '',//选中的费率
            MPMONTH_list_selected: {}, //选中值
            totalAmount: 0, //总金额
            Trial_table: [],//试算结果展示
            IccMpprm: '',//分期计划数据
            DialogVisible: false,//多期试算表格弹窗显示
            DialogVisible1: false,
            TrialDataList: [],//费率表数据
            multipleSelection: [],//存放表格多选选中的数据数组
            secConfirmDialogVisible: false, // 二次确认弹窗是否显示
            secondConfirm: { // 二次确认字段
                handleNum: '',
                totalAmount: '',
                months: '',
                pmMethod: '',
            },
            step3Page: false, // 办理结果页面是否显示
            resultList: [],//存放多选处理结果
            RtnindFlag: '',
            result4072: {},
            speechList: [],//话术列表
            selectedList: [],
            MenuId: '',
        };
    },
    computed: mapState({
        defaultParams: state => state.common.defaultParams, // 接口默认参数
        cardInfo_3004: state => state.common.cardInfo_3004,
        cardAccountInfo_3001: state => state.common.cardAccountInfo_3001, // 卡账户信息
        cardList_3601: state => state.common.cardList_3601,
        defaultpinFlag: state => state.common.pinFlag,
        AccountionTYPE_INFO: state => state.common.AccountionTYPE_INFO, //账户类别列表
        isCurrentMenuInfo: state => state.menu.isCurrentMenuInfo,
        businessMenu: state => state.menu.businessMenu,
    }),
    async mounted() {
        this.MenuId = this.$route.params.id || '';
        await this.init();
        // 获取信用计划编号 下拉选择列表
        //await this.getBaseData({ dictValue: 'MPNO' }, 'CREDNOLIST');
        this.CREDNOLIST = await getDictSelectList('MPNO', this);
        this.dailyForm.CARDNO = this.cardInfo_3004.CARDNO;
        // 获取账户类别
        // console.log(this.cardList_3601, 'this.cardList_3601')
        // this.accountType = await getAccountTypeName(this.cardList_3601, this.cardInfo_3004, this);

        //初始化查询信用计划列表
        // await this.searchData();
        await this.getspeechList();
    },
    filters: {
        // 日期格式转换
        formatDate(val) {
            const text = `${val}`;
            return moment(text).format('YYYY-MM-DD');
        },
        // 获取日期时间转换
        getFormatDate(time, date) {
            let res = '';
            let str = '';
            let tmp = '';
            const timeStr = time.toString().trim();
            if (date !== 0) {
                tmp = `00000000${timeStr}`;
                tmp = tmp.substring(tmp.length - 8, tmp.length);
                str = tmp.substring(0, 2).concat(':').concat(tmp.substring(2, 4)).concat(':')
                    .concat(tmp.substring(4, 6));
            }
            if (date) {
                res = `${moment(`${date}`).format('YYYY-MM-DD')} ${str}`;
            }
            return res;
        },
        // 卡号末四位自动补0
        formatCardend(val) {
            return val.toString().padStart(4, '0');
        },
    },
    methods: {
        async init() {
            console.log("默认账户类别：" + this.cardInfo_3004.CATEGORY);
            console.log("默认账户：" + this.cardInfo_3004.CARDNO);
            this.searchForm.accttype = this.cardInfo_3004.CATEGORY + '';

            // 分期期数
            this.MPMONTH_list = await getDictSelectList('MPMONTH', this);

            this.searchForm.cardno = this.cardInfo_3004.CARDNO;
            this.changeCardList(this.searchForm.accttype);
            this.dailyForm.CREDNO = '';
        },
        // 获取分期计划对应的数据
        async getInitData() {
            let params = {
                pageNum: 1,
                pageSize: 10,
                itemNo: this.dailyForm.CREDNO,
            };
            await this.$post.MpprmPlan.pageIccMpprm(params).then((res) => {
                if (res.data.success) {
                    this.IccMpprm = res.data.content.records[0];
                    console.log('分期计划__IccMpprm', this.IccMpprm);
                } else {
                    this.$alert('分期计划数据请求失败', '提示', {
                        customClass: 'warning', type: 'warning',
                    });
                }
            });
        },
        changeCardList(val) {
            console.log("当前账户类型：" + val);
            let hasDefault = false; //是否包含默认卡
            this.cardList = [];
            this.cardList_3601.forEach((item) => {
                if (item.CATEGORY + '' === val) {
                    this.cardList.push(item);
                    if (item.CARDNBR === this.cardInfo_3004.CARDNO) {
                        hasDefault = true;
                    }
                }
            });

            //包含默认卡，卡号显示默认卡，不包含，显示cardList里第一张卡号
            if (hasDefault) {
                this.searchForm.cardno = this.cardInfo_3004.CARDNO;
            } else {
                this.searchForm.cardno = this.cardList[0].CARDNBR;
            }


        },
        //根据菜单id查询话术列表
        async getspeechList() {
            console.log("this.isCurrentMenuInfo.id", this.isCurrentMenuInfo.id);
            console.log("this.MenuId", this.MenuId);
            var checkParam = {
                'id': this.MenuId || this.isCurrentMenuInfo.id,
            };
            this.$post.busiMenu.getlistByMenuId(checkParam).then((res) => {
                console.log("话术查询结果：", res);
                if (res.status === 200) { // http通讯成功
                    if (res.data.status == 0) { // 业务请求成功
                        this.speechList = res.data.content;
                    }
                }
            });
        },
        handleSelectionChange(val) {
            this.selectedList = val;
        },
        // 获取信用计划编号列表
        async getBaseData(params, target) {
            this.$post.common.getBaseDataList(params).then((res) => {
                this[target] = res.data.content;
                this.dailyForm.CREDNO = (res.data.content !== null && res.data.content.length > 0) ? res.data.content[0].code : '';
            });
            console.log(" this.dailyForm.CREDNO :", this.dailyForm.CREDNO);
        },

        // 下拉改变信用计划编号的值
        async getCREDNOValue(val) {
            console.log('================下拉改变信用计划编号的值val', val);
            console.log('================下拉改变信用计划编号的值this.dailyForm.CREDNO', this.dailyForm.CREDNO);
            this.MPMONTH_Option = [];
            this.MPMONTH_Option_one = {};
            this.dailyForm.NBRMTHS = '';
            this.Trial_table = [];
            this.step3Page = false;
            //重新查询信用计划列表
            await this.searchData();

        },

        // 查分分期期数和费率，手续费分摊方式 3-0.024-1,6-0.0468-1  
        // MPMONTH_list: '',//分期期数列表
        // MPFEE_list: '',//费率
        // 手续费支付方式
        splitStringValue() {
            const nbrMthsArray = this.IccMpprm.nbrMths.split(','); //期数
            const appFeeratioArray = this.IccMpprm.appFeeratio.split(',');//费率
            const interestRateArray = this.IccMpprm.interestRate.split(',');//利率
            const paytypeArray = this.IccMpprm.paytype.split(',');//手续费分摊方式
            const MPoption = [];
            nbrMthsArray.forEach((item, index) => {
                // const itemArray = item.split('-');
                console.log('nbrMthsArray', item, index);
                MPoption[index] = {
                    MPMONTH: item,//分期期数
                    MPFEE: appFeeratioArray[index],////费率
                    PMmethod: paytypeArray[index],//，手续费分摊方式
                    interest: interestRateArray[index],//利率
                    label: item + '期--费率:' + (appFeeratioArray[index] * 100).toFixed(2) + '%',
                }
            })
            this.MPMONTH_Option = JSON.parse(JSON.stringify(MPoption));
            console.log('MPMONTH_Option', this.MPMONTH_Option);
        },

        // 可消费分期付款的交易明细查询
        async searchData() {
            this.trailTable = [];
            this.isChecked = {};
            this.pagingDataList = [];
            this.PURDATE = '';
            this.VALDATE = '';
            this.PURTIME = '';
            this.TRANNO = '';
            if (this.dailyForm.CREDNO === '') {

                this.$alert('请选择分期计划编号！', '提示', {
                    customClass: 'warning', type: 'warning',
                });
                return;
            }

            // 每次变更查询同时，重新查询费率期数表
            await this.getInitData();
            this.splitStringValue();

            this.handleGetListData('first');
        },
        async get_3076() {
            this.defaultParams.sysHead.busiName = '可消费分期付款交易申请查询';
            this.dailyForm.CARDNO = this.cardInfo_3004.CARDNO;
            this.showTrial = true;
            this.isLoading = true;
            // 3076 配置请求头
            const appBody_3076 = {
                CARDNBR: this.cardInfo_3004.CARDNO, // '6250522500000291'卡号,
                MPSTS: 2, // 查询条件 0：无 1：已申请消费分期 2：未申请消费分期
                OPTION: 1, // 查询类型 1－按卡号查询 2－按证件号码查询
                CUSTRNBR: '', // 证件号码 查询类型为2时，必填
                CATE: `${this.cardInfo_3004.CATEGORY}`, // 账户类别 查询类型为2时，必填
                CREDNO: this.dailyForm.CREDNO, // 信用计划编号
                RTNIND: this.pagingDataList.length === 0 ? '' : 1, // 翻页标志 首次传空， 翻页传1
                PINFLAG: this.defaultpinFlag,
                PIN: '',
                VALDATE: this.VALDATE,
                PURDATE: this.PURDATE,
                PURTIME: this.PURTIME,
                TRANNO: this.TRANNO,
            };
            // 需要一个接口获取分期期数数据
            // this.setMonthRate = await getInstalmentList(this.dailyForm.CREDNO, this);
            this.tryData = [
                {
                    OUTFLAG: '',
                    CORPUS: 0,
                    REMONTHFEE: 0,
                    ALLMONTHSFEE: 0,
                    ALLCOUNTFEE: 0,
                    MPIRR: 0,
                },
            ];
            let bool = false;
            if (this.pagingDataList.length == 0) bool = true;
            const result_3076 = await get_3xxx(
                '3076',
                '可消费分期付款交易申请查询',
                appBody_3076,
                this,
                true,
                bool
            );

            // if (!result_3121) return false;
            // 如果传过来的为空, 则无下翻页 ,将下翻按钮禁用
            if (!result_3076) {
                if (this.pagingDataList.length != 0) {
                    this.$message.warning('已经到最后一条数据');
                }
                this.nextButtonFlag = true;
                this.trailTable = [];
                return false;
            }

            this.trailTable = result_3076.body.appBody.dataList ? result_3076.body.appBody.dataList : [];

            // this.trailTable = [{ AMOUNT: 3000, AMTFLAG: '+', AUTHCODE: '', CARDEND: '1015', CURRNUM: '156', DESLINE1: '111', DESLINE2: '', MONTHNBR: 380, MPAUSTS: '00', MPFLAG: 0, NBRMTHS: 0, PURDATE: 20210728, PURDATE1: 728, PURTIME: 16061877, REVS: '', TRANNO: 781129, TRANTYPE: 1110, VALDATE: 20210728 },
            // { AMOUNT: 2000, AMTFLAG: '+', AUTHCODE: '', CARDEND: '1015', CURRNUM: '156', DESLINE1: '111', DESLINE2: '', MONTHNBR: 380, MPAUSTS: '00', MPFLAG: 0, NBRMTHS: 0, PURDATE: 20210728, PURDATE1: 728, PURTIME: 16061877, REVS: '', TRANNO: 781130, TRANTYPE: 1110, VALDATE: 20210728 },
            // { AMOUNT: 3600, AMTFLAG: '+', AUTHCODE: '', CARDEND: '1015', CURRNUM: '156', DESLINE1: '111', DESLINE2: '', MONTHNBR: 380, MPAUSTS: '00', MPFLAG: 0, NBRMTHS: 0, PURDATE: 20210728, PURDATE1: 728, PURTIME: 16061877, REVS: '', TRANNO: 781131, TRANTYPE: 1110, VALDATE: 20210728 }];

            // 翻页设置
            ChangePage(this, ['PURDATE', 'VALDATE', 'PURTIME', 'TRANNO'], 'trailTable', 10);
        },
        // 3077分期付款交易明细查询
        handleGetListData(type) {

            if (type === 'first') {

                this.RtnindFlag = '';
                this.VALDATE = '';
                this.PURDATE = '';
                this.PURTIME = '';
                this.TRANNO = '';
                this.resultlist = [];
            }
            this.defaultParams.sysHead.busiName = '可消费分期付款交易申请查询';
            this.dailyForm.CARDNO = this.cardInfo_3004.CARDNO;
            this.showTrial = true;
            this.isLoading = true;
            // 3076 配置请求头
            const appBody_3076 = {
                CARDNBR: this.cardInfo_3004.CARDNO, // '6250522500000291'卡号,
                MPSTS: 2, // 查询条件 0：无 1：已申请消费分期 2：未申请消费分期
                OPTION: 1, // 查询类型 1－按卡号查询 2－按证件号码查询
                CUSTRNBR: '', // 证件号码 查询类型为2时，必填
                CATE: '', // 账户类别 查询类型为2时，必填
                CREDNO: this.dailyForm.CREDNO, // 信用计划编号
                RTNIND: this.pagingDataList.length === 0 ? '' : 1, // 翻页标志 首次传空， 翻页传1
                PINFLAG: this.defaultpinFlag,
                PIN: '',
                VALDATE: this.VALDATE,
                PURDATE: this.PURDATE,
                PURTIME: this.PURTIME,
                TRANNO: this.TRANNO,
            };
            const defaultParams = JSON.parse(JSON.stringify(this.defaultParams));
            defaultParams.body.appHead.tranCode = '3076';
            defaultParams.body.appBody = appBody_3076;
            // 3077交易

            this.$post.common.transPort(defaultParams).then((res) => {
                if (res.status === 200) {
                    const result = JSON.parse(res.data.jsonRes);
                    if (result.sysHead.rspCd === '000000') {
                        this.resultlist.push(...result.body.appBody.dataList);

                        if (result.body.appBody.RTNIND === '1') {

                            this.VALDATE = result.body.appBody.dataList[result.body.appBody.dataList.length - 1].VALDATE;
                            this.PURDATE = result.body.appBody.dataList[result.body.appBody.dataList.length - 1].PURDATE;
                            this.PURTIME = result.body.appBody.dataList[result.body.appBody.dataList.length - 1].PURTIME;
                            this.TRANNO = result.body.appBody.dataList[result.body.appBody.dataList.length - 1].TRANNO;
                            // 修改翻页标志 
                            this.RtnindFlag = result.body.appBody.RTNIND;
                            this.handleGetListData();

                        } else {
                            this.isLoading = false;
                            console.log('this.InstallmentInfo_3076', this.resultlist);
                            this.trailTable = this.resultlist;
                            console.log("trailTable", this.trailTable);
                            // this.$store.commit('common/UPDATE_CARD_INSTALLMENT_INFO', this.InstallmentInfo_3077);
                        }
                    } else {
                        this.isLoading = false;
                        // const errorMsg = `错误代码：${result.sysHead.rspCd}, 错误信息：${result.sysHead.rspMsg}`;
                        // this.$alert(errorMsg, result.sysHead.rspDesc, {
                        //     customClass: 'error',
                        // });
                    }
                } else {
                    this.isLoading = false;

                }
            });
        },

        // 未出账单查询
        unBillChecked() {
            this.$router.push('/businessSystem/unBillChecked');
        },
        // 分期付款交易明细查询
        onMptransQuery() {
            this.$router.push('/instalment/InstallmentPayDetail');
        },
        // 选择需要申请分期付款的交易明细条目
        getCard(val) {
            if (!val) return false;
            this.currentRow = val; //选中行数据
            this.dailyForm.MPAMT = this.currentRow.AMOUNT; //更新金额（选中计划明细的金额）
        },
        // 计划列表多选值修改
        multipleChange(val) {
            this.multipleSelection = val;
            let tamt = 0;
            for (let index = 0; index < val.length; index++) {
                const element = val[index];
                tamt = tamt + element.AMOUNT;
            }
            this.totalAmount = tamt;

            this.handleGetComputeMP(this.MPMONTH_Option_one);
        },
        // 切换信用计划编号
        changeData() {
            this.isChecked = {};
            this.tryData = [
                {
                    OUTFLAG: '',
                    CORPUS: 0,
                    REMONTHFEE: 0,
                    ALLMONTHSFEE: 0,
                    ALLCOUNTFEE: 0,
                    MPIRR: 0,
                    TRYDATA1: 0,
                    TRYDATA2: 0,
                    TRYDATA3: 0,
                    TRYDATA4: 0,
                },
            ];
        },

        // 申请
        handleApplication() {
            if (this.multipleSelection.length === 0) {
                this.$alert('请先选择要办理的消费记录！', '提示', {
                    customClass: 'warning', type: 'warning',
                });
                return;
            }
            if (this.dailyForm.NBRMTHS === '') {
                this.$alert('请先选择分期期数！', '提示', {
                    customClass: 'warning', type: 'warning',
                });
                return;
            }

            this.secondConfirm.handleNum = this.multipleSelection.length;
            this.secondConfirm.totalAmount = this.totalAmount;
            this.secondConfirm.months = this.dailyForm.NBRMTHS.MPMONTH;
            this.secondConfirm.pmMethod = this.dailyForm.NBRMTHS.PMmethod == "1" ? "按月摊还" : "一次性收取";
            console.log("this.selectedList.length", this.selectedList.length);
            if (this.selectedList.length != this.speechList.length) {
                this.$alert('话术尚未全部勾选！', '提示', {
                    customClass: 'warning', type: 'warning',
                });
                return;
            }
            this.secConfirmDialogVisible = true;
        },
        // 二次确认确定
        async secConfirmYes() {
            // 申请交易发送成功后，隐藏二次确认弹窗，显示申请结果页面
            this.secConfirmDialogVisible = false;
            this.resultList = [{
                amount: '',
                months: '',
                pmMethod: this.dailyForm.NBRMTHS.PMmethod == "1" ? "按月摊还" : "一次性收取",
                handleResult: ''
            }];

            const pro = new Promise((resolve, reject) => {
                this.get4072(resolve, reject);
            });
            pro.then((dataList) => {
                console.log("dataList_then", dataList);
                this.resultList = dataList;
            })




            this.step3Page = true;
            // 申请之后重新查询
            this.searchData();
        },

        get4072(resolve, reject) {
            let dataList = [];
            this.multipleSelection.forEach(async (item) => {
                const appBody4072 = {
                    CARDNBR: this.cardInfo_3004.CARDNO,
                    OPTION: 1,
                    OPERTP: 0,
                    PINFLAG: this.defaultpinFlag,
                    CREDNO: this.dailyForm.CREDNO,
                    VALDATE: item.VALDATE, // 原始交易入账日期
                    PURDATE: item.PURDATE, // 原始交易记录日期
                    PURTIME: item.PURTIME, // 原始交易消费时间
                    TRANNO: item.TRANNO, // 原始交易流水号
                    TRANTP: item.TRANTYPE, // 原始交易类型
                    NBRMTHS: this.dailyForm.NBRMTHS.MPMONTH || '', // 分期期数
                    BILLAMT: item.AMOUNT,
                    CURRNUM: '156',
                };

                console.log('appBody4072:', appBody4072);
                const params4072 = JSON.parse(JSON.stringify(this.defaultParams));
                params4072.body.appHead.tranCode = '4072';
                params4072.body.appBody = appBody4072;

                await this.$post.common.transPort(params4072).then((res) => {
                    if (res.status === 200) {
                        const result = JSON.parse(res.data.jsonRes);
                        console.log(result, '响应数据 -- 4072');

                        if (result.sysHead.rspCd === '000000') {
                            dataList.push({
                                amount: item.AMOUNT,
                                months: this.dailyForm.NBRMTHS.MPMONTH,
                                pmMethod: this.dailyForm.NBRMTHS.PMmethod == "1" ? "按月摊还" : "一次性收取",
                                handleResult: '交易成功'
                            });
                        } else {
                            console.log(item, '响应数据 -- 4072');
                            dataList.push({
                                amount: item.AMOUNT,
                                months: this.dailyForm.NBRMTHS.MPMONTH,
                                pmMethod: this.dailyForm.NBRMTHS.PMmethod == "1" ? "按月摊还" : "一次性收取",
                                handleResult: '交易失败，' + result.sysHead.rspMsg
                            });
                            console.log(item, '响应数据 -- 4072', this.repayresultlData);
                        }
                    } else {
                        dataList.push({
                            amount: item.AMOUNT,
                            months: this.dailyForm.NBRMTHS.MPMONTH,
                            pmMethod: this.dailyForm.NBRMTHS.PMmethod == "1" ? "按月摊还" : "一次性收取",
                            handleResult: '请求失败'
                        });
                    }
                });
                console.log('dataList', dataList);

                resolve(dataList);
            });
        },
        // 将组件返回的false赋值给当前
        close(data) {
            this.showsuccess = data;
        },
        // 上下页切换
        handleChangePage(type) {
            this.currentRow = null;
            this.isChecked = {};
            this.tryData = [
                {
                    OUTFLAG: '', //存期数
                    CORPUS: 0,
                    REMONTHFEE: 0,
                    ALLMONTHSFEE: 0,
                    ALLCOUNTFEE: 0,
                    MPIRR: 0,
                },
            ];
            if (type === 'pre') { // 切换到上一页
                if (this.currentPageIndex - 2 < 0) {
                    this.pagingDataList = []; // 清空缓存 申请编号 -> 相当于首次查询
                    this.VALDATE = '';
                    this.PURDATE = '';
                    this.PURTIME = '';
                    this.TRANNO = '';
                } else {
                    this.currentPageIndex = this.currentPageIndex - 2;
                    this.VALDATE = this.pagingDataList[this.currentPageIndex].VALDATE;
                    this.PURDATE = this.pagingDataList[this.currentPageIndex].PURDATE;
                    this.PURTIME = this.pagingDataList[this.currentPageIndex].PURTIME;
                    this.TRANNO = this.pagingDataList[this.currentPageIndex].TRANNO;
                }
                this.get_3076();
            } else { // 切换到下一页
                this.get_3076();
            }
        },

        // 1、手续费支付方式。0：首期支付；1：分摊支付
        // 2、总手续费 = 费率*本金
        // 3、总还款额  = 总手续费+本金
        // 4、每期手续费（分摊支付方式） = 总手续费/分期期数
        // 5、月还款额（分摊支付方式）= 本金/分期期数+总手续费/分期期数

        // 6、如果是首期支付，首期还款额 = 本金/分期期数 + 总手续费
        // 	月还款额 = 本金/分期期数 
        // item.MPMONTH //分期期数
        // 获取分期期数 下拉选择数据
        handleGetComputeMP(item) {
            this.MPMONTH_Option_one = item;
            console.log("this.MPMONTH_Option_one", this.MPMONTH_Option_one);
            if (!this.dailyForm.CREDNO) {
                this.$alert('信用计划编号为空，请先选择信用计划编号！', '提示', {
                    customClass: 'warning', type: 'warning',
                });
                return;
            }

            if (this.dailyForm.NBRMTHS === '') {

                return;
            }

            this.Trial_table = [];
            const MPFEENum = this.MPMONTH_Option_one.MPFEE * 1;//费率
            const MPMONTHNum = this.MPMONTH_Option_one.MPMONTH * 1;//期数
            //this.MPMONTH_Option_one = item;
            const MPAMT_value = (this.totalAmount || 0) * 1; //分期金额（多选各项累加金额），改动前：this.formData.MPAMT
            const totalHandling = (MPFEENum * MPAMT_value).toFixed(2);//总手续费
            const monthsPrincipal = (MPAMT_value / MPMONTHNum).toFixed(2);//每月本金、
            const monthlyService = (totalHandling * 1 / MPMONTHNum).toFixed(2);//每月手续费、
            this.totalHandling_Value = totalHandling;
            const totalRepayment = (totalHandling * 1 + MPAMT_value).toFixed(2);//总还款额
            let monthlyPayment = 0;
            let fstPayment = 0;
            if (item.PMmethod === "1") {
                // 每期手续费（分摊支付方式）
                // const EachIssue = (totalHandling / item.MPMONTH).toFixed(2);
                // 月还款额
                monthlyPayment = ((MPAMT_value / item.MPMONTH).toFixed(2) * 1 + (totalHandling / item.MPMONTH).toFixed(2) * 1).toFixed(2);
                // this.Trial_table = `首期还款额:${monthlyPayment}￥, 月还款额:${monthlyPayment}￥, 总手续费:${totalHandling}￥, 本金+手续费总额:${totalRepayment}￥`;
            } else {
                // 首期还款额

                // 月还款额
                monthlyPayment = (MPAMT_value / item.MPMONTH).toFixed(2);
                fstPayment = parseFloat(monthlyPayment) + parseFloat(totalHandling);

                // this.Trial_table = `首期还款额:${FirstIssue}￥, 月还款额:${monthlyPayment}￥, 总手续费:${totalHandling}￥, 本金+手续费总额:${totalRepayment}￥`;
            }
            // 总还款额、总手续费、每月本金、每月手续费、每月还款额
            this.Trial_table.push({
                totalRepayment: parseFloat(totalRepayment).toFixed(2),//总还款额、
                totalHandling: parseFloat(totalHandling).toFixed(2),//总手续费、
                monthsPrincipal: parseFloat(monthsPrincipal).toFixed(2),//每月本金、
                monthlyService: parseFloat(monthlyService).toFixed(2),//每月手续费、
                monthlyPayment: parseFloat(monthlyPayment).toFixed(2),//每月还款额
                fstPayment: parseFloat(fstPayment).toFixed(2),//每月还款额
            })
        },
        // 多期数试算结果
        handleClicksuInfo() {

            if (this.multipleSelection.length == 0) {
                this.$alert('请先选择要办理的消费记录！', '提示', {
                    customClass: 'warning', type: 'warning',
                });
                return;
            }

            //1拆分字典值
            const trial = [];
            this.MPMONTH_Option.forEach((item) => {
                this.getTralDataList(item, trial);
            })
            console.log('trial', trial);
            this.TrialDataList = trial;
            console.log('TrialDataList期数列表', this.TrialDataList);
            if (this.MPMONTH_Option[0].PMmethod === '1') {
                this.DialogVisible = true;
            } else {
                this.DialogVisible1 = true;
            }

        },
        // 拼装多种期数的费率数据结构
        getTralDataList(item, trial) {
            console.log('item', item);
            const MPFEENum = item.MPFEE * 1;//费率
            const MPAMT_value = (this.totalAmount || 0) * 1; //分期金额（多选各项累加金额），改动前：this.formData.MPAMT
            const totalHandling = (MPFEENum * MPAMT_value).toFixed(2);//总手续费 费用总额
            const totalRepayment = (totalHandling * 1 + MPAMT_value).toFixed(2);//总还款额
            let monthlyPayment = 0;////每期分摊金额
            let FirstIssue = 0;//首期还款额 第一期分摊金额
            let monthlyPrincipal = 0;//每期分摊本金
            let monthlyCost = 0;//每期分摊费用

            // 每期分摊本金
            monthlyPrincipal = (MPAMT_value / item.MPMONTH).toFixed(2);
            if (item.PMmethod === "1") {
                // 每期手续费（分摊支付方式）

                //每期分摊费用   =  费用总额/ item.MPMONTH
                monthlyCost = (totalHandling / item.MPMONTH).toFixed(2);

                // 月还款额 每期分摊金额
                monthlyPayment = ((MPAMT_value / item.MPMONTH).toFixed(2) * 1 + (totalHandling / item.MPMONTH).toFixed(2) * 1).toFixed(2);
            } else {
                // 首期还款额  第一期分摊金额 = 每期分摊本金+费用总额
                FirstIssue = parseFloat(monthlyPrincipal) + parseFloat(totalHandling);
            }
            const itemList = {
                MPMONTH: item.MPMONTH,//
                Bystages: MPAMT_value,//分期金额
                totalHandling: totalHandling,////总手续费 费用总额
                totalRepayment: totalRepayment,//总还款额
                rate: (MPFEENum * 100).toFixed(2) + '%',//费率
                monthlyPrincipal: monthlyPrincipal,//每期分摊本金
                monthlyCost: monthlyCost,//每期分摊费用
                FirstIssue: parseFloat(FirstIssue).toFixed(2),//第一期分摊金额
                monthlyPayment: monthlyPayment,// 每期分摊金额
                interest: item.interest,//利率
            }
            trial.push(itemList)
        },

        applicationRecords() {
            this.MenuId = getBusinessMenuId('/carPeriodic/mptransrecordqry', this.businessMenu);
            console.log('this.MenuId____', this.MenuId);
            this.$router.push({ name: 'mptransrecordqry', path: '/carPeriodic/mptransrecordqry', params: { id: this.MenuId } });

        },

    },
};
</script>

<style  scoped lang="scss">
.ConsumeInstallment {
    .insAppli-contnair .el-form-item {
        text-align: center;
    }
    .footer {
        text-align: center;
        margin-top: 10px;
        margin-bottom: 18px;
    }
}
</style>
